#!coding=utf-8
from django.core.cache import cache
import datetime
import urllib2
import json
import requests
from urllib import quote
import math
from urllib2 import urlopen
from shop import settings, const
#获取授权Token
def getAccToken():
    appid = getattr(settings,'WEIXIN_APPID')
    secret = getattr(settings,'WEIXIN_SECRET')
    if cache.get('WEIXIN_TOKEN') == None :
        #重新获取token
        get_token_url = 'https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=%s&secret=%s' % (appid,secret)
        req = urllib2.Request(url=get_token_url)
        f = urllib2.urlopen(req)
        stringjson = f.read()
        accToken=json.loads(stringjson)['access_token']
        cache.set('WEIXIN_TOKEN', accToken,6000)
        return accToken
    else:
        return cache.get('WEIXIN_TOKEN')
# def getAccToken():
#     appid = getattr(settings,'WEIXIN_APPID')
#     secret = getattr(settings,'WEIXIN_SECRET')
#     if cache.get('WEIXIN_TOKEN') == None:
#         #重新获取token
#         get_token_url = 'https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=%s&secret=%s' % (appid,secret)
#         req = urllib2.Request(url=get_token_url)
#         f = urllib2.urlopen(req)
#         stringjson = f.read()
#         accToken=json.loads(stringjson)['access_token']
#         cache.set('WEIXIN_TOKEN', accToken,6000)
#         return accToken
#     else:
#         return cache.get('WEIXIN_TOKEN')
    
def getJssdkTicket():
    if cache.get('WEIXIN_JSSDK_TICKET') == None or \
        (datetime.datetime.now() - cache.get('WEIXIN_JSSDK_TICKET_GETAT')).seconds >= 7000:
        acctoken=getAccToken();
        weixin_jssdk_ticket_url = "https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=%s&type=jsapi"%acctoken; 
        req = urllib2.Request(url=weixin_jssdk_ticket_url)
        f = urllib2.urlopen(req)
        strjson=f.read()
        accToken=json.loads(strjson)['ticket']
        cache.set('WEIXIN_JSSDK_TICKET', accToken,6000)
        cache.set('WEIXIN_JSSDK_TICKET_GETAT',datetime.datetime.now(),10000)
        
        return accToken
    else:
        return cache.get('WEIXIN_JSSDK_TICKET')
    
    
def getWebAccToken(code):
    appid = getattr(settings,'WEIXIN_APPID')
    secret = getattr(settings,'WEIXIN_SECRET')
    WebAccToken_url="https://api.weixin.qq.com/sns/oauth2/access_token?appid=%s&secret=%s&code=%s&grant_type=authorization_code" % (appid,secret,code)
    print WebAccToken_url
    data=requests.get(WebAccToken_url);
    res=json.loads(data.content);
    openid=res["openid"]
    return openid
    
# print getWebAccToken('001Kku341Xm2c02LyZ2413Uw341Kku3x')
# print getJssdkTicket()    

#path为二维码的存放路径，改目录要保证存在  ，scene_id为二维码的参数值
def getWithParasDimensionalCode(path,scene_id):
    TOKEN=getAccToken()
    url='https://api.weixin.qq.com/cgi-bin/qrcode/create?access_token='+TOKEN
    data='{"action_name":"QR_LIMIT_SCENE", "action_info":{"scene": {"scene_id": %s}}}'%(scene_id)
#     response = requests.post(url, data=json.dumps(data))
    response = requests.post(url, data)
    jsoncontent = json.loads(response.content)
    if jsoncontent.has_key('ticket'):
        ticket=jsoncontent['ticket']
        dimcodeurl="https://mp.weixin.qq.com/cgi-bin/showqrcode?ticket="+quote(ticket)
        open(path,'wb').write(urllib2.urlopen(dimcodeurl).read())
    else:
        print "获取二维码路径失败"

#计算两个gps坐标点的距离，返回单位为m
def calcDistance(fLati1,fLong1,fLati2,fLong2):
    def rad(d):
        PI = 3.1415926535898
        return d * PI / 180.0
    
    EARTH_RADIUS = 6378.137
    radLat1 = rad(fLati1)
    radLat2 = rad(fLati2)
    a = radLat1 - radLat2
    b = rad(fLong1) - rad(fLong2)
    s = 2 * math.asin(math.sqrt(pow(math.sin(a/2),2) + math.cos(radLat1)*math.cos(radLat2)*pow(math.sin(b/2),2)))
    s = s * EARTH_RADIUS
    s = (int)(s * 10000000) / 10000
    return s

#拉取关注用户列表
def getWXUserList():
    TOKEN=getAccToken()
    url='https://api.weixin.qq.com/cgi-bin/user/get?access_token='+TOKEN
#     response = requests.get(url)
#https 的get请求
    res = urlopen(url);
    jsoncontent = json.loads(res.read())
    print jsoncontent
    
    
#设置模板消息行业类型
def setIndus():
    TOKEN=getAccToken()
    url="https://api.weixin.qq.com/cgi-bin/template/api_set_industry?access_token="+TOKEN;
    data='{"industry_id1":"13","industry_id2":"14"}';
    
    response = requests.post(url, data)
    jsoncontent = json.loads(response.content)
    
    return jsoncontent

def getIndus():
    TOKEN=getAccToken()
    url="https://api.weixin.qq.com/cgi-bin/template/get_industry?access_token="+TOKEN;
    response = requests.get(url)
    jsoncontent = json.loads(response.content)
    
    return jsoncontent

def getAllTemp():
    TOKEN=getAccToken()
    url="https://api.weixin.qq.com/cgi-bin/template/get_all_private_template?access_token="+TOKEN;
    response = requests.get(url)
    jsoncontent = json.loads(response.content)
    
    return jsoncontent
def sedTempMsg(msg):
    TOKEN=getAccToken()
    url="https://api.weixin.qq.com/cgi-bin/message/template/send?access_token="+TOKEN;
    response = requests.post(url, msg)
    jsoncontent = json.loads(response.content)
    return jsoncontent
    
    
def getWXCustinfo(openid):
    access_token=getAccToken()
    posturl = "https://api.weixin.qq.com/cgi-bin/user/info?access_token=%s&openid=%s&lang=zh_CN " %(access_token,openid);
    req=urllib2.urlopen(posturl)
    return json.load(req)
